package com.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.common.utils.Result;
import com.entity.Card;
import com.entity.TaskStore;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.mapper.CardMapper;
import com.query.CardQuery;
import com.service.CardService;
import com.service.TaskStoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wty
 * @since 2020-11-18
 */
@Service
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements CardService {

    @Autowired
    private TaskStoreService taskStoreService;

    /**
     * 根据条件添加卡片
     * @param cardQuery
     * @return
     */
    @Override
    public Result addCard(CardQuery cardQuery) {
        //单独添加卡片
        Card card=new Card()    ;
        BeanUtils.copyProperties(cardQuery,card);
        boolean flag = this.insert(card);
        if(flag){
            //根据任务添加卡片
            Integer taskStoreId = cardQuery.getTaskStoreId();
            if(null!=taskStoreId){
                Wrapper<TaskStore> wrOne =new EntityWrapper<>();
                wrOne.eq("id",taskStoreId);
                TaskStore taskStore = taskStoreService.selectOne(wrOne);
                if(null!=taskStore){
                    String cardId = taskStore.getCardId();
                    if(!StringUtils.isEmpty(cardId)){
                        List<String> strings = JSONArray.parseArray(cardId, String.class);
                        strings.add(card.getId().toString());
                        String cards = JSONObject.toJSONString(strings);
                        taskStore.setCardId(cards);
                        taskStoreService.updateById(taskStore);
                    }else{
                        List<String>  strings2=new ArrayList<>();
                        strings2.add(card.getId().toString());
                        String cards = JSONObject.toJSONString(strings2);
                        taskStore.setCardId(cards);
                        taskStoreService.updateById(taskStore);
                    }

                }
            }
        }
        return Result.success();
    }

    /**
     * 根据条件获取卡片
     * @param cardQuery
     * @return
     */
    @Override
    public Result getCardList(CardQuery cardQuery) {
        Wrapper<Card> wr=new EntityWrapper<>();
        List<Card> cards = this.selectList(wr);
        return  Result.success(cards);
    }
}
